package com.laijiale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.laijiale.constant.ML;
import com.laijiale.dto.*;
import com.laijiale.entity.Course;
import com.laijiale.exception.ServiceException;
import com.laijiale.mapper.EpisodeMapper;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.laijiale.entity.Season;
import com.laijiale.mapper.SeasonMapper;
import com.laijiale.service.SeasonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import vo.SeasonSimpleListVO;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static com.laijiale.entity.table.CourseTableDef.COURSE;
import static com.laijiale.entity.table.EpisodeTableDef.EPISODE;
import static com.laijiale.entity.table.SeasonTableDef.SEASON;

/**
 * 季次表 服务层实现。
 *
 * @author laijiale
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "season")
public class SeasonServiceImpl extends ServiceImpl<SeasonMapper, Season>  implements SeasonService{
        @Autowired
        private EpisodeMapper episodeMapper;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(SeasonInsertDTO dto) {
        //标题查重
        if(QueryChain.of(mapper).where(SEASON.TITLE.eq(dto.getTitle())).exists()){
            throw new ServiceException("季次标题已存在") ;
        }
        //组装entity实体类
        Season season= BeanUtil.copyProperties(dto,Season.class);
        season.setCreated(LocalDateTime.now());
        season.setUpdated(LocalDateTime.now());
        return mapper.insert(season)>0;

    }

    @Cacheable(key = "#p0",condition = "#p0 !=null",unless = "#result ==null")
    @Override
    public Season select(Long id) {
        RelationManager.addQueryRelations("course","category","episodes");
        return mapper.selectOneWithRelationsById(id);
    }
    @Cacheable(key = "#root.methodName",
            unless = "#result == null"
    )
    @Override
    public List<SeasonSimpleListVO> simpleList() {
        List<SeasonSimpleListVO> seasonSimpleListVOS=QueryChain.of(mapper).listAs(SeasonSimpleListVO.class);
        return seasonSimpleListVOS;
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition ="#p0 != null",
            unless = "#result == null")
    @Override
    public Page<Season> page(SeasonPageDTO dto) {
        RelationManager.addQueryRelations("course","category","episodes");
        QueryChain<Season> queryChain = QueryChain.of(mapper)
                .orderBy(SEASON.IDX.asc(), SEASON.ID.desc());

        // title 条件
        String title = dto.getTitle();
        if(ObjectUtil.isNotNull(title)) {
            queryChain.where(SEASON.TITLE.like(title));
        }
        //courseId条件
        Long fkCourseId =dto.getFkCourseId();
        if (ObjectUtil.isNotNull(fkCourseId)){
            queryChain.where(SEASON.FK_COURSE_ID.eq(fkCourseId));
        }
        return queryChain.withRelations().page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }
    @CacheEvict(allEntries = true)
    @Override
    public boolean update(SeasonUpdateDTO dto) {

        // 标题查重
        if (QueryChain.of(mapper).
                where(SEASON.TITLE.eq(dto.getTitle()))
                .and(SEASON.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("季次标题已存在");
        }

        // 组装 entity 实体类
        Season season = BeanUtil.copyProperties(dto, Season.class);
        // 设置 entity 默认值
        season.setUpdated(LocalDateTime.now());
        return UpdateChain.of(season).where(SEASON.ID.eq(season.getId())).update();
    }
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        List<Long> episodeIds =QueryChain.of(episodeMapper).select(EPISODE.ID).where(EPISODE.FK_SEASON_ID.eq(id))
                .objListAs(Long.class);
        //存在季记录，批删
        this.clearEpisode(episodeIds);
        return mapper.deleteById(id) > 0;

    }
    private void clearEpisode(List<Long> episodeIds) {
        if (ObjectUtil.isNotEmpty(episodeIds)){
            if (episodeMapper.deleteBatchByIds(episodeIds)<=0){
                throw new ServiceException("集次删除失败");
            }
        }
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        List<Long> episodes =QueryChain.of(episodeMapper).select(EPISODE.ID).where(EPISODE.FK_SEASON_ID.in(ids))
                .objListAs(Long.class);
        this.clearEpisode(episodes);
        return mapper.deleteBatchByIds(ids) > 0;
    }


}
